package com.hnyfkj.jyindustry;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentListener;

public class SwingDemo extends JFrame {

    MyJPanel mp;
    int index;
    int startX = -1920;
    int startY;
    ImageIcon[] imgs = {
            new ImageIcon("src/images/1.jpg"),
//            new ImageIcon("src/images/2.jpg"),
//            new ImageIcon("src/images/3.jpg"),
//            new ImageIcon("src/images/4.jpg"),
//            new ImageIcon("src/images/5.jpg"),
//            new ImageIcon("src/images/6.jpg"),
//            new ImageIcon("src/images/7.jpg"),
//            new ImageIcon("src/images/8.jpg"),
    };

    public SwingDemo() {
        mp = new MyJPanel();
        this.add(mp);
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setTitle("窗口");
        this.setVisible(true);

        Timer timer = new Timer(50, e -> {
            animate();
            mp.repaint();
        });
        timer.start();
    }

    private void animate() {
        int width = mp.getWidth();
        int iconWidth = imgs[index].getIconWidth();

        System.out.println("startx:" + startX + " , width: " + width + " , iconWidth: " + iconWidth);
        //等于1920的时候停止
        if (startX == 1920) {
            startX = -1920;
            return;
        }


        //无线滑动
        if (startX > (iconWidth + width)) {
            startX = 0;
        } else {
            startX += 4;
        }
    }

    public static void main(String[] args) {
        new SwingDemo();
    }

    class MyJPanel extends JPanel {

        @Override
        public synchronized void addComponentListener(ComponentListener l) {
            super.addComponentListener(l);
        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            g.drawImage(imgs[index % imgs.length].getImage(), startX, startY, this);
            //index++;
        }
    }

}